package cn.ac.siom.query.action;

import cn.ac.siom.query.service.IFun_bookService;
import cn.ac.siom.query.util.action.DefaultAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ac.siom.query.action.PDFdownload.readInputStream;

@SuppressWarnings("unchecked")
@Controller
@RequestMapping(value = "/home/*")
public class Fun_bookAction extends DefaultAction {

    @Resource
    private IFun_bookService fun_bookService;

    @Autowired
    private Config config;

    @ResponseBody
    @RequestMapping(value = "findPhoto_Fun_book", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List findPhoto_http(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        insertAccessinfo(request,"首页学术著作");
        List<Map<String, byte[]>> list = new ArrayList<Map<String, byte[]>>();
        List<String> fun_book = this.fun_bookService.listHttp_photo();
        for (String findPhoto_Fun_book : fun_book) {
            try {
                URL url = new URL(config.b_cover + findPhoto_Fun_book);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setConnectTimeout(5000);
                conn.setDoOutput(true);
                //得到输入流
                InputStream inputStream = conn.getInputStream();
                //获取自己数组
                byte[] getData = readInputStream(inputStream);
                String[] type = findPhoto_Fun_book.split("\\.");
                String types = type[type.length - 1];
                Map<String, byte[]> map = new HashMap<String, byte[]>();
                map.put("data:image/" + types + ";base64,", getData);
                list.add(map);
            } catch (Exception e) {
                continue;
            }
        }
        return list;
    }

    @Override
    public String getText() {
        return null;
    }
}